package org.lan.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.lan.entity.Group;
import org.lan.entity.User;
import org.lan.service.IUserService;

import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    private IUserService userService;

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = authenticationToken.getPrincipal().toString();
        User user = userService.findUserByUsername(username);
        if (user == null) {
            throw new UnknownAccountException();
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
        return authenticationInfo;
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = principalCollection.getPrimaryPrincipal().toString();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        int userId = userService.findUserByUsername(username).getId();

        Set<String> permissionStringSet = userService.findResourcePermissionString(userId);
        permissionStringSet.forEach((permissionString -> {
            authorizationInfo.addStringPermission(permissionString);
        }));

        List<Group> groups = userService.findUserGroupGroupByUserId(userId);
        groups.forEach((group -> {
            authorizationInfo.addRole(group.getGroupName());
        }));

        return authorizationInfo;
    }
}
